/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="common-page platform-manage__page">
        <div class="platform-manage__tabs">
            <div class="platform-manage__box">
                <div :class="activeNo===1?'tabs__button active':'tabs__button'"
                     @click="active(1)">
                    <i class="iconzhuzhuangtunormal icon iconfont"/>
                    {{ _('资源运维') }}
                </div>
                <div :class="activeNo===2?'tabs__button active':'tabs__button'"
                     @click="active(2)">
                    <i class="icon-comp-user sf-comp-iconfont"/>
                    {{ _('用户管理') }}
                </div>
            </div>
        </div>
        <div class="platform-manage__body">
            <resource-detail-user
                v-show="activeNo===1"
                ref="resource"
                from-page="user"
                @refresh-resource="_refreshResource"/>

            <div v-show="activeNo===2">
                <div class="user-manage__head">
                    <p class="user-manage__page-title">用户列表</p>
                    <div>
                        <sf-button
                            class="btn-blank"
                            icon-cls="iconsip-refresh"
                            @click="_refresh">
                            <lang>刷新</lang>
                        </sf-button>
                        <sf-searchfield
                            v-model="searchParams.keyword"
                            class="pull-right"
                            placeholder="请输入关键字"
                            @trigger="_startSearch"
                            @clear="_startSearch"/>
                    </div>
                </div>
                <div class="table-data">
                    <sf-grid>
                        <sf-toolbar ref="toolbar">
                            <sf-button
                                ref="submit"
                                class="creat-button btn-blank"
                                icon-cls="iconxinzeng2"
                                @click="_addUser">
                                <lang>新增用户</lang>
                            </sf-button>
                        </sf-toolbar>
                        <sf-table
                            ref="table"
                            class="user-manage__table"
                            :options="options_fix"
                            :default-height="750"
                            @pagechange="_onPageChange"
                            @sizechange="_onSizeChange">
                            <sf-table-column :default-width="30"
                                             type="index">
                                <lang>序号</lang>
                            </sf-table-column>
                            <sf-table-column data-index="username"
                                             :default-width="60">
                                <lang>用户名称</lang>
                            </sf-table-column>
                            <sf-table-column data-index="cpuNum" :default-width="80">
                                <lang>CPU使用/总数（核）</lang>
                            </sf-table-column>
                            <sf-table-column data-index="vGpuMemory" :default-width="80">
                                <lang>显存分配/总数（GB）</lang>
                            </sf-table-column>
                            <sf-table-column data-index="memorySize" :default-width="80">
                                <lang>内存分配/总数（GB）</lang>
                            </sf-table-column>
                            <sf-table-column data-index="volumeSize" :default-width="80">
                                <lang>存储分配/总数（GB）</lang>
                            </sf-table-column>
                            <sf-table-column data-index="dateSpace" :default-width="80">
                                <lang>数据空间分配/总数（GB）</lang>
                            </sf-table-column>

                            <sf-table-column
                                data-index="updateTime"
                                :default-width="80">
                                <lang>上次使用</lang>
                            </sf-table-column>
                            <sf-table-column data-index="role"
                                             :default-width="60">
                                <lang>管理员权限</lang>
                            </sf-table-column>
                            <sf-table-column data-index="opr"
                                             :default-width="100">
                                <lang>操作</lang>
                            </sf-table-column>
                            <template slot="role"
                                      slot-scope="{ value }">
                                <span>{{ !!value ? _("是") : _("-") }}</span>
                            </template>

                            <template slot="cpuNum" slot-scope="{ record }">
                                <span
                                    :title="`${record.allocatedCpuNum}/${record.cpuNum}`">{{ `${record.allocatedCpuNum}/${record.cpuNum}`
                                    }}</span>
                            </template>
                            <template slot="vGpuMemory" slot-scope="{ record }">
                                <span
                                    :title="`${record.allocatedVGpuMemory}/${record.vGpuMemory}`">{{ `${record.allocatedVGpuMemory}/${record.vGpuMemory}`
                                    }}</span>
                            </template>
                            <template slot="memorySize" slot-scope="{ record }">
                                <span
                                    :title="`${record.allocatedMemorySize}/${record.memorySize}`">{{ `${record.allocatedMemorySize}/${record.memorySize}`
                                    }}</span>
                            </template>
                            <template slot="volumeSize" slot-scope="{ record }">
                                <span
                                    :title="`${record.allocatedVolumeSize || 0}/${record.volumeSize}`">{{ `${record.allocatedVolumeSize || 0}/${record.volumeSize}`
                                    }}</span>
                            </template>
                            <template slot="dateSpace" slot-scope="{ record }">
                                <span
                                    :title="haveDataSpace(record)?`${record.usedCapacity  || 0}/${record.totalCapacity}`:''">
                                    {{ haveDataSpace(record) ? `${record.usedCapacity || 0}/${record.totalCapacity}` : '-'
                                    }}
                                </span>
                            </template>


                            <!--额外操作-->
                            <template slot="opr"
                                      slot-scope="{ record }">
                                <div class="table-opr">
                                    <link-btn :ref="'hoverLink'+record.userId">操作</link-btn>
                                    <sf-menu trigger="hover" :default-target="'hoverLink'+record.userId">
                                        <sf-menu-item @click="_editUser(record)">
                                            <lang>编辑</lang>
                                        </sf-menu-item>
                                        <sf-menu-item @click="_deleteUser(record)">
                                            <lang>删除</lang>
                                        </sf-menu-item>
                                    </sf-menu>
                                </div>
                            </template>
                        </sf-table>
                    </sf-grid>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="less">
.platform-manage__page {
    overflow-y: auto;

    .table-data {
        height: auto;
    }

    .table-data .sfv-grid .sfv-table {
        flex: none;
    }

    .user-manage__page-title {
        color: #14161A;
        font-size: 16px;
        padding: 0 12px;
        height: 48px;
        line-height: 48px;
        font-weight: bold;
    }

    .platform-manage__tabs {
        height: 87px;
        background-color: #FFFFFF;
        display: flex;
        justify-content: center;
        align-items: center;

        .platform-manage__box {
            display: flex;
            padding: 4px;
            background-color: #f2f3f5;
            border-radius: 4px;
        }

        .tabs__button {
            width: 128px;
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #F2F3F5;
            border-radius: 5px;
            cursor: pointer;
        }

        .active {
            background-color: #2C2A2A;
            color: #FFFFFF;
        }
    }

    .platform-manage__body {
        padding: 0 40px;

        .user-manage__head {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .btn-blank {
                margin-right: 21px;;
            }
        }

        .user-manage__table {
            .sfv-table_row:hover {
                .table-opr {
                    display: block;
                }
            }
            .sfv-table_row-selected {
                .table-opr {
                    display: block;
                }
            }

            .table-opr {
                display: none;
            }
        }
    }
}
</style>

<script>

/**
 * Created by zhb on 2020/6/16
 */

import urlAdapter from 'src/home/mod_common/auth_url_adapter';
import addUserForm from './components/add_user_form.vue';

import resourceDetailUser from 'src/home/mod_cluster/common/resource/resource_detail_user.vue';
import LinkBtn from 'src/components/link_btn';
import store from 'src/vuex/store';

const USER_URLS = {
    get: urlAdapter('user'),
    delete: urlAdapter('user'),
    post: urlAdapter('user'),
    edit: urlAdapter('user'),
    getResource: urlAdapter('resource')
};

const PAGE_COUNT = 10;


let userID = store.state.userId;


export default {
    components: {
        resourceDetailUser,
        LinkBtn
    },

    data() {
        return {
            searchParams: {
                pageSize: PAGE_COUNT,
                pageNum: 0,
                keyword: ''
            },
            options_fix: {
                bufferView: false,
                selectionHide: true,

                // 配置这个后才可以实现保持勾选状态
                idProperty: 'id',
                pagination: {
                    activePage: 1,
                    pageSize: PAGE_COUNT,
                    pageSizes: [Number('10'), Number('20'), Number('50')]
                }
            },
            isEdsStorage: true,
            remainSourceData: {},
            activeNo: 1,
        };
    },

    computed: {},
    mounted() {
        this._refreshResource();
    },
    methods: {
        haveDataSpace(record) {
            return !!record.dataSpaceName;
        },

        active(no) {
            this.activeNo = no;
        },

        _refreshResource() {
            this.getResource();
            this.refreshGrid();
        },
        async getResource() {
            this.$mask();

            let jsonData = await this.$ajax.get(USER_URLS.getResource);
            this.$unmask();
            let {success, msg, data} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('删除失败'));
            }
            this.remainSourceData = data;
            this.$refs.resource && this.$refs.resource.setJsonValue(data);
        },
        _canOperateUser(props) {
            return props.username === userID;
        },

        // 新增服务
        _createAddUserForm() {
            return this.$modal(addUserForm, {
                autoDestroy: true
            });
        },
        _addUser() {
            let formWin = this._createAddUserForm();
            let vm = this;
            formWin.formRoot.reset();
            formWin.open({
                title: _('新增用户'),
                height: 780,
                data: {
                    pvcList: this.pvcList,
                    isEdit: false,
                    isOwn: false,
                    resourceNums: {
                        cpu: vm.remainSourceData.totalCpu,
                        memory: vm.remainSourceData.totalMemory,
                        gpu: vm.remainSourceData.remainedAllocatedTotalGpu,
                        workspace: 10000,
                        datasetCapacity: 100,
                        dataSpaceCapacity: 20000,
                    }
                },
                submit: () => {
                    let ajaxParams = formWin.formRoot.getJsonValue();
                    vm.ajaxSubmitUser(ajaxParams, formWin);
                }
            });
        },

        // 新增/编辑算法的卡片信息
        async ajaxSubmitUser(params, formWin, fetch = 'post') {
            formWin.$mask();
            const QUERY_URL = fetch === 'post' ? USER_URLS.post : `${USER_URLS.post}/${params.userId}`;
            let jsonData = await this.$ajax[fetch](QUERY_URL, params);
            formWin.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('保存失败'));
            }
            this.$ok(_('保存成功'));
            formWin.hide();


            this._refreshResource();

        },
        _editUser(record) {
            let formWin = this._createAddUserForm();
            formWin.formRoot.setJsonValue(record);
            let vm = this;
            let isOwn = record.username === userID;
            formWin.open({
                title: _('编辑用户'),
                height: 780,
                data: {
                    isEdit: true,
                    isOwn,
                    resourceNums: {
                        cpu: vm.remainSourceData.totalCpu,
                        memory: vm.remainSourceData.totalMemory,
                        gpu: vm.remainSourceData.remainedAllocatedTotalGpu + record.gpuNum,
                        workspace: 10000,
                        datasetCapacity: 100,
                        dataSpaceCapacity: 20000,
                    }
                },
                submit: () => {
                    if (formWin.formRoot.haveDataSpace && !formWin.formRoot.showDataSpace) {
                        this.$confirm({
                            title: _('提示'),
                            subTitle: _('确定要删除该用户的数据空间吗？'),
                            msg: _('删除后数据将无法恢复。'),
                            icon: 'warning',
                            callback: actionName => {
                                if (actionName === 'submit') {
                                    let ajaxParams = formWin.formRoot.getJsonValue();
                                    vm.ajaxSubmitUser(ajaxParams, formWin, 'put');
                                }
                            }
                        });
                    }else {
                        let ajaxParams = formWin.formRoot.getJsonValue();
                        vm.ajaxSubmitUser(ajaxParams, formWin, 'put');
                    }
                }
            });
        },

        async refreshGrid() {
            this.$mask();

            let jsonData = await this.$ajax.get(USER_URLS.get, this.searchParams);
            this.$unmask();
            let table = this.$refs.table;
            let {success, msg, data} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('删除失败'));
            }

            table && table.getPagination().setTotal(data.total);
            table && table.loadData(data.list || []);


        },

        _refresh() {
            this.refreshGrid();
        },

        _startSearch() {
            this.refreshGrid();
        },

        _onPageChange(pageNum) {
            Object.assign(this.searchParams, {
                pageNum: pageNum - 1
            });
            this.refreshGrid();
        },
        _onSizeChange(nowPageIndex, nowPageSize) {
            Object.assign(this.searchParams, {
                pageNum: nowPageIndex - 1,
                pageSize: nowPageSize
            });
            this.refreshGrid();
        },
        _deleteUser(record) {
            let item = record;
            let params = {};
            let title = '';
            if (item) {
                params.userId = item.userId;
                title = item.username;
            }
            this.$confirm({
                title: _('提示'),
                subTitle: _('确定要删除{0}这个用户吗？', title),
                msg: '',
                autoClose: true,
                callback: actionName => {
                    if (actionName === 'submit') {
                        this.ajaxDeleteUser(params);
                    }
                }
            });
        },
        async ajaxDeleteUser(params) {
            this.$mask();
            let jsonData = await this.$ajax.delete(`${USER_URLS.delete}/${params.userId}`);
            this.$unmask();
            let {success, msg} = jsonData;
            if (!success) {
                return this.$showErr(msg || _('删除失败'));
            }
            this.$ok(_('删除成功'));
            this._refreshResource();
        }

    }
};
</script>
